import { useErrorHandler } from '@/utils/errorHandler';
import { computed, ref } from 'vue';
import { useFormValidation } from './useFormValidation';
import { useLoading } from './useLoading';

/**
 * 表单CRUD操作 Composable
 * @param {Object} options - 配置选项
 * @returns {Object} 表单CRUD管理对象
 */
export function useFormCrud(options = {}) {
    const {
        apiService,
        initialData = {},
        validationRules = {},
        onSuccess = null,
        onError = null,
        resetAfterSubmit = true
    } = options;

    const errorHandler = useErrorHandler();
    const { isLoading, withLoading } = useLoading();

    // 表单状态
    const dialogVisible = ref(false);
    const mode = ref('create'); // 'create' | 'edit' | 'view'
    const currentItem = ref(null);

    // 使用表单验证
    const {
        formData,
        errors,
        isValid,
        hasErrors,
        isDirty,
        validateForm,
        resetForm,
        handleSubmit
    } = useFormValidation(initialData, validationRules);

    /**
     * 打开创建对话框
     */
    const openCreateDialog = () => {
        mode.value = 'create';
        currentItem.value = null;
        resetForm();
        dialogVisible.value = true;
    };

    /**
     * 打开编辑对话框
     * @param {Object} item - 要编辑的项目
     */
    const openEditDialog = (item) => {
        mode.value = 'edit';
        currentItem.value = { ...item };

        // 填充表单数据
        Object.keys(formData).forEach(key => {
            if (item.hasOwnProperty(key)) {
                formData[key] = item[key];
            }
        });

        dialogVisible.value = true;
    };

    /**
     * 打开查看对话框
     * @param {Object} item - 要查看的项目
     */
    const openViewDialog = (item) => {
        mode.value = 'view';
        currentItem.value = { ...item };

        // 填充表单数据（只读）
        Object.keys(formData).forEach(key => {
            if (item.hasOwnProperty(key)) {
                formData[key] = item[key];
            }
        });

        dialogVisible.value = true;
    };

    /**
     * 关闭对话框
     */
    const closeDialog = () => {
        dialogVisible.value = false;
        mode.value = 'create';
        currentItem.value = null;
        resetForm();
    };

    /**
     * 保存数据
     */
    const save = async () => {
        try {
            let result;

            if (mode.value === 'create') {
                result = await handleSubmit(async (data) => {
                    return await apiService.create(data);
                });
            } else if (mode.value === 'edit') {
                result = await handleSubmit(async (data) => {
                    const id = currentItem.value.id || currentItem.value.Id;
                    return await apiService.update(id, data);
                });
            }

            if (result) {
                const action = mode.value === 'create' ? '创建' : '更新';
                errorHandler.showSuccess(`${action}成功`);

                if (onSuccess) {
                    await onSuccess(result, mode.value);
                }

                if (resetAfterSubmit) {
                    closeDialog();
                }

                return result;
            }
        } catch (error) {
            const action = mode.value === 'create' ? '创建' : '更新';
            errorHandler.handleNetworkError(error, action);

            if (onError) {
                onError(error, mode.value);
            }

            throw error;
        }
    };

    /**
     * 删除项目
     * @param {Object} item - 要删除的项目
     * @param {Function} confirmFn - 确认函数
     */
    const deleteItem = withLoading(async (item, confirmFn = null) => {
        try {
            // 如果提供了确认函数，先确认
            if (confirmFn) {
                const confirmed = await confirmFn(item);
                if (!confirmed) {
                    return;
                }
            }

            const id = item.id || item.Id;
            await apiService.delete(id);

            errorHandler.showSuccess('删除成功');

            if (onSuccess) {
                await onSuccess(item, 'delete');
            }

            return true;
        } catch (error) {
            errorHandler.handleNetworkError(error, '删除');

            if (onError) {
                onError(error, 'delete');
            }

            throw error;
        }
    });

    /**
     * 批量删除
     * @param {Array} items - 要删除的项目列表
     * @param {Function} confirmFn - 确认函数
     */
    const bulkDelete = withLoading(async (items, confirmFn = null) => {
        if (!items || items.length === 0) {
            errorHandler.showWarning('请选择要删除的项目');
            return;
        }

        try {
            // 如果提供了确认函数，先确认
            if (confirmFn) {
                const confirmed = await confirmFn(items);
                if (!confirmed) {
                    return;
                }
            }

            // 如果API支持批量删除
            if (apiService.bulkDelete) {
                const ids = items.map(item => item.id || item.Id);
                await apiService.bulkDelete(ids);
            } else {
                // 逐个删除
                await Promise.all(items.map(item => {
                    const id = item.id || item.Id;
                    return apiService.delete(id);
                }));
            }

            errorHandler.showSuccess(`成功删除 ${items.length} 个项目`);

            if (onSuccess) {
                await onSuccess(items, 'bulkDelete');
            }

            return true;
        } catch (error) {
            errorHandler.handleNetworkError(error, '批量删除');

            if (onError) {
                onError(error, 'bulkDelete');
            }

            throw error;
        }
    });

    /**
     * 复制项目
     * @param {Object} item - 要复制的项目
     */
    const duplicateItem = (item) => {
        const copyData = { ...item };

        // 移除ID字段
        delete copyData.id;
        delete copyData.Id;

        // 添加复制标识
        if (copyData.name) {
            copyData.name = `${copyData.name} (副本)`;
        } else if (copyData.title) {
            copyData.title = `${copyData.title} (副本)`;
        }

        mode.value = 'create';
        currentItem.value = null;

        // 填充表单数据
        Object.keys(formData).forEach(key => {
            if (copyData.hasOwnProperty(key)) {
                formData[key] = copyData[key];
            }
        });

        dialogVisible.value = true;
    };

    // 计算属性
    const dialogTitle = computed(() => {
        switch (mode.value) {
            case 'create':
                return '新建';
            case 'edit':
                return '编辑';
            case 'view':
                return '查看';
            default:
                return '';
        }
    });

    const isReadonly = computed(() => mode.value === 'view');
    const isCreateMode = computed(() => mode.value === 'create');
    const isEditMode = computed(() => mode.value === 'edit');
    const isViewMode = computed(() => mode.value === 'view');
    const canSave = computed(() => !isReadonly.value && isValid.value && !isLoading.value);

    return {
        // 状态
        dialogVisible: computed(() => dialogVisible.value),
        mode: computed(() => mode.value),
        currentItem: computed(() => currentItem.value),
        isLoading,

        // 表单状态
        formData,
        errors,
        isValid,
        hasErrors,
        isDirty,

        // 计算属性
        dialogTitle,
        isReadonly,
        isCreateMode,
        isEditMode,
        isViewMode,
        canSave,

        // 方法
        openCreateDialog,
        openEditDialog,
        openViewDialog,
        closeDialog,
        save,
        deleteItem,
        bulkDelete,
        duplicateItem,
        validateForm,
        resetForm
    };
}

/**
 * 确认对话框 Composable
 * @returns {Object} 确认对话框管理对象
 */
export function useConfirmDialog() {
    const visible = ref(false);
    const title = ref('');
    const message = ref('');
    const confirmCallback = ref(null);
    const cancelCallback = ref(null);
    const severity = ref('warn'); // 'warn' | 'danger' | 'info'

    /**
     * 显示确认对话框
     * @param {Object} options - 对话框选项
     * @returns {Promise<boolean>} 用户选择结果
     */
    const confirm = (options = {}) => {
        return new Promise((resolve) => {
            title.value = options.title || '确认操作';
            message.value = options.message || '您确定要执行此操作吗？';
            severity.value = options.severity || 'warn';

            confirmCallback.value = () => {
                visible.value = false;
                resolve(true);
            };

            cancelCallback.value = () => {
                visible.value = false;
                resolve(false);
            };

            visible.value = true;
        });
    };

    /**
     * 确认删除操作
     * @param {string|Array} items - 项目名称或项目列表
     * @returns {Promise<boolean>} 用户选择结果
     */
    const confirmDelete = (items) => {
        const isArray = Array.isArray(items);
        const count = isArray ? items.length : 1;
        const itemName = isArray ? `${count} 个项目` : (items.name || items.title || '该项目');

        return confirm({
            title: '确认删除',
            message: `您确定要删除 ${itemName} 吗？此操作不可撤销。`,
            severity: 'danger'
        });
    };

    return {
        visible: computed(() => visible.value),
        title: computed(() => title.value),
        message: computed(() => message.value),
        severity: computed(() => severity.value),
        confirmCallback: computed(() => confirmCallback.value),
        cancelCallback: computed(() => cancelCallback.value),
        confirm,
        confirmDelete
    };
}
